package com.yvan.upload.aliyunoss;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.GenericRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.Cleanup;
import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.util.Properties;
import java.util.UUID;

/**
 * @author Yvan
 * @Description: 阿里云OSS文件上传工具类
 * @date 2016年11月3日 下午12:03:24
 */
public class OSSUploadUtil {
    /**连接区域地址*/
    private static String endpoint;
    /**连接keyId*/
    private static String accessKeyId;
    /**连接秘钥*/
    private static String accessKeySecret;
    /**需要存储的bucketName*/
    private static String bucketName;
    /**图片保存路径*/
    private static String picLocation;
    private static final String CONFIG_PROPERTIES = "aliyunoss_client.properties";

    public static void env(String activeDir) {
        if (StringUtils.isNotBlank(endpoint)
                && StringUtils.isNotBlank(accessKeyId)
                && StringUtils.isNotBlank(accessKeySecret)
                && StringUtils.isNotBlank(bucketName)
                && StringUtils.isNotBlank(picLocation)
        ) {
            return;
        }
        try {
            String resourcePath = StringUtils.isBlank(activeDir) ? CONFIG_PROPERTIES : activeDir + File.separatorChar + CONFIG_PROPERTIES;
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            Properties properties = new Properties();
            @Cleanup
            InputStream in = loader.getResourceAsStream(resourcePath);
            properties.load(in);
            endpoint = properties.getProperty("oss.endpoint");
            bucketName = properties.getProperty("oss.bucketName");
            picLocation = properties.getProperty("oss.picLocation");
            accessKeyId = properties.getProperty("oss.accessKeyId");
            accessKeySecret = properties.getProperty("oss.accessKeySecret");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param file 文件
     * @param fileType 文件后缀
     * @return String 文件地址
     * @Description: OSS单文件上传
     */
    public static String uploadFile(File file, String fileType) {
        //文件名，根据UUID来
        String fileName = picLocation + UUID.randomUUID().toString().toUpperCase().replace("-", "") + "." + fileType;
        return putObject(file, fileType, fileName);
    }

    /**
     * @param fileUrl 需要删除的文件url
     * @return boolean 是否删除成功
     * @Description: 单文件删除
     */
    public static boolean deleteFile(String fileUrl) {
        //根据url获取bucketName
        String bucketName = OSSUploadUtil.getBucketName(fileUrl);
        //根据url获取fileName
        String fileName = OSSUploadUtil.getFileName(fileUrl);
        if (bucketName == null || fileName == null) {
            return false;
        }
        OSSClient ossClient = null;
        try {
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            GenericRequest request = new DeleteObjectsRequest(bucketName).withKey(fileName);
            ossClient.deleteObject(request);
        } catch (Exception oe) {
            oe.printStackTrace();
            return false;
        } finally {
            assert ossClient != null;
            ossClient.shutdown();
        }
        return true;
    }

    /**
     * @param file 文件对象
     * @param fileType 文件类型
     * @param fileName 文件名
     * @return String
     * @Description: 上传文件
     */
    private static String putObject(File file, String fileType, String fileName) {
        //默认null
        String url;
        OSSClient ossClient = null;
        try {
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            InputStream input = new FileInputStream(file);
            // 创建上传Object的Metadata
            ObjectMetadata meta = new ObjectMetadata();
            // 设置上传内容类型
            meta.setContentType(OSSUploadUtil.contentType(fileType));
            // 被下载时网页的缓存行为
            meta.setCacheControl("no-cache");
            //创建上传请求
            PutObjectRequest request = new PutObjectRequest(bucketName, fileName, input, meta);
            ossClient.putObject(request);
            //上传成功再返回的文件路径
            url = endpoint.replaceFirst("http://", "http://" + bucketName + ".") + "/" + fileName;
        } catch (OSSException | ClientException | FileNotFoundException oe) {
            oe.printStackTrace();
            return null;
        } finally {
            assert ossClient != null;
            ossClient.shutdown();
        }
        return url;
    }

    /**
     * @param fileType 文件类型
     * @return String
     * @Description: 获取文件类型
     */
    private static String contentType(String fileType) {
        fileType = fileType.toLowerCase();
        String contentType;
        switch (fileType) {
            case "bmp":
                contentType = "image/bmp";
                break;
            case "gif":
                contentType = "image/gif";
                break;
            case "png":
            case "jpeg":
            case "jpg":
                contentType = "image/jpeg";
                break;
            case "html":
                contentType = "text/html";
                break;
            case "txt":
                contentType = "text/plain";
                break;
            case "vsd":
                contentType = "application/vnd.visio";
                break;
            case "ppt":
            case "pptx":
                contentType = "application/vnd.ms-powerpoint";
                break;
            case "doc":
            case "docx":
                contentType = "application/msword";
                break;
            case "xml":
                contentType = "text/xml";
                break;
            case "mp4":
                contentType = "video/mp4";
                break;
            default:
                contentType = "application/octet-stream";
                break;
        }
        return contentType;
    }

    /**
     * @param fileUrl 文件url
     * @return String bucketName
     * @Description: 根据url获取bucketName
     */
    private static String getBucketName(String fileUrl) {
        String http = "http://";
        String https = "https://";
        int httpIndex = fileUrl.indexOf(http);
        int httpsIndex = fileUrl.indexOf(https);
        int startIndex ;
        if (httpIndex == -1) {
            if (httpsIndex == -1) {
                return null;
            } else {
                startIndex = httpsIndex + https.length();
            }
        } else {
            startIndex = httpIndex + http.length();
        }
        int endIndex = fileUrl.indexOf(".oss-");
        return fileUrl.substring(startIndex, endIndex);
    }

    /**
     * @param fileUrl 文件url
     * @return String fileName
     * @Description: 根据url获取fileName
     */
    private static String getFileName(String fileUrl) {
        String str = "aliyuncs.com/";
        int beginIndex = fileUrl.indexOf(str);
        if (beginIndex == -1) {
            return null;
        }
        return fileUrl.substring(beginIndex + str.length());
    }
}
